Isomorphic strings¶
Time: O(N); Space: O(1); easy
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters.
No two characters may map to the same character but a character may map to itself.
Example 1:
Input: s = “egg”, t = “add”
Output: True
Example 2:
Input: s = “foo”, t = “bar”
Output: False
Example 3:
Input: s = “paper”, t = “title”
Output: True
Note:
You may assume both s and t have the same length.
[4]:
class Solution1(object):
"""
Time: O(N)
Space: O(1)
"""
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
s2t, t2s = {}, {}
for p, w in zip(s, t):
if w not in s2t and p not in t2s:
s2t[w] = p
t2s[p] = w
elif w not in s2t or s2t[w] != p:
# Contradict mapping.
return False
return True
[5]:
sol = Solution1()
s = "egg"
t = "add"
assert sol.isIsomorphic(s, t) == True
s = "foo"
t = "bar"
assert sol.isIsomorphic(s, t) == False
s = "paper"
t = "title"
assert sol.isIsomorphic(s, t) == True
[6]:
class Solution2(object):
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
return self.halfIsom(s, t) and self.halfIsom(t, s)
def halfIsom(self, s, t):
lookup = {}
for i in range(len(s)):
if s[i] not in lookup:
lookup[s[i]] = t[i]
elif lookup[s[i]] != t[i]:
return False
return True
[7]:
sol = Solution2()
s = "egg"
t = "add"
assert sol.isIsomorphic(s, t) == True
s = "foo"
t = "bar"
assert sol.isIsomorphic(s, t) == False
s = "paper"
t = "title"
assert sol.isIsomorphic(s, t) == True